package com.gateway.predicates;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.BeforeRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @version 1.0
 * @author: yu.tan
 * @date: 2020/11/19 22:04
 * @Description: 这是一个自定义的路由断言工厂类
 * 要求：
 * 1、名字必须是 配置+RoutePredicateFactory
 * 2、必须继承AbstractRoutePredicateFactory<配置类></>
 */
//@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public static final String DATETIME_KEY = "datetime";

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    //读取配置文件的参数值，赋值到配置类的属性上
    public List<String> shortcutFieldOrder() {
        //这个位置的顺序必须跟配置文件中的值的顺序对应
        return Arrays.asList("minAge", "maxAge");
    }

    //断言逻辑
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //1、接收传入的age参数
                String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                //2、先判断是否为空
                if (StringUtils.isNoneBlank(age)) {
                    //3、路由逻辑
                    int parseAge = Integer.parseInt(age);
                    if (parseAge < config.getMaxAge() && parseAge > config.getMinAge()) {
                        return true;
                    } else {
                        return false;
                    }
                }

                return false;
            }
        };
    }

    //配置类。用于接收配置文件对应的参数
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Config {
        private int minAge;
        private int maxAge;
    }
}

